import sqlite3, re, os, sys, getopt, datetime
from support.utils.file.picture import Picture
from support.utils.dbms.db import DBHelper
from support.ui.console import Log
from support.ui.board.dashboard import DashBoard

SUPPORT_FILE_TYPE = ['.jpeg','.png','.jpg','.mp4','.mov']

def printHelpInfo():
    print("幫助信息\n\n")
    print("usage: python {} [options] [db options]\n".format(sys.argv[0]))
    print("options:\n")
    print("-t\t : 仅显示计划删除的文件\n")
    print("db options:\n")
    print("--dbpath\t : 数据库存放路径，默认为脚本所在目录\n")
    print("--dbname\t : 数据库名字，默认为albuminfo.db\n")

def findDuplicateFiles():
    helper = DBHelper(dbpath, dbname)
    #ret = helper.execute('''SELECT album.Name AS name, picture.Local AS path, album.hash AS hash FROM album JOIN picture ON album.id=picture.id GROUP BY album.hash HAVING COUNT(album.hash)>1;''')
    ret = helper.execute('''SELECT album.Name AS name, picture.Local AS path, album.hash AS hash FROM album JOIN picture ON album.id=picture.id;''')
    return sorted(ret, key=sortDuplicateFiles)


def sortDuplicateFiles(item):
    return item[2]


if __name__ == "__main__":
    opts,args = getopt.getopt(sys.argv[1:], '-h-t', ["help","dbpath=","dbname="])
    testmode= False
    dbpath = os.path.dirname(os.path.abspath(__file__))
    dbname = "albuminfo.db"
    Log.Level = Log.DEBUG
    #Log.Mode = Log.MODE_SYSTEM
    if(not opts):
        printHelpInfo()
        sys.exit()
    for opt_name, opt_value in opts:
        if(opt_name in ('-h','--help')):
            printHelpInfo()
            sys.exit()
        elif(opt_name == '-t'):
            testmode=True 
        elif(opt_name == '--dbpath'):
            dbpath = opt_value
        elif(opt_name == '--dbname'):
            dbname = opt_value
    filelist = findDuplicateFiles()
    for file in filelist:
        print("{}|{}".format(file[0], file[1]))
